﻿using MyK3CloudCore.IOC.Attributes;
using MyK3CloudCore.IOC.DataEntity.PresetEntity;
using MyK3CloudCore.IOC.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace MyK3CloudCore.IOC.K3Client;

public partial class K3CloudApiClient
{
    /// <summary>
    /// 简单账表查询
    /// </summary>
    public async Task<string> GetSysReportDataAsync(string formid, SysReportModel data)
    {
        return await ExecuteAsync("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.GetSysReportData", formid, data);
    }
    /// <summary>
    /// 报表API接口;库存账龄分析报表;物料收发明细报表;物料收发汇总报表;
    /// https://vip.kingdee.com/article/301363894805890816?productLineId=1
    /// </summary>
    /// <param name="formid"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<string> GetSCMReportDataAsync(ReportParamModel data)
    {
        return await ExecuteAsync("Kingdee.K3.SCM.WebApi.ServicesStub.StockReportQueryService.GetReportData,Kingdee.K3.SCM.WebApi.ServicesStub", data);
    }

    public async Task<List<T>> GetSysReportDataAsync<T>(SysReportModel data1)
    {
        var formId = typeof(T).GetAlias();
        List<T> list = new();
        PropertyInfo[] fieldProperties = typeof(T).GetProperties().Where(t => t.GetCustomAttributes(typeof(ignoreAttribute), true).Length == 0).ToArray();
        string field = string.Join(",", fieldProperties.Select(x => x.GetCustomAttribute<AliasAttribute>()?.Name ?? x.Name).ToArray());
        data1.FieldKeys = field;
        var result = await GetSysReportDataAsync(formId, data1);
        var obj = JsonConvert.DeserializeObject<SysReportResult>(result);
        if (obj == null) return default;
        if (!obj.Result.IsSuccess) throw new Exception(JsonConvert.SerializeObject(obj.Result.ResponseStatus.Errors));
        if (obj.Result.Rows.Count == 0) return default;
        var data = obj.Result.Rows;

        for (int i = 0; i < data.Count; i++)
        {
            var item = Activator.CreateInstance<T>();
            for (int j = 0; j < fieldProperties.Length; j++)
            {
                if (data[i][j] == null) { continue; }
                object propertyValue = ConvertNullableType(data[i][j], item.GetType().GetProperty(fieldProperties[j].Name).PropertyType);
                SetPropertyValue(item, fieldProperties[j].Name, propertyValue);
            }
            list.Add(item);
        }
        return list;
    }

    public async Task<DataTable> GetSCMReportDataTableAsync(ReportParamModel data1)
    {
        var result = await GetSCMReportDataAsync(data1);
        var obj = JsonConvert.DeserializeObject<SCMReportResult>(result);
        if (obj == null) return default;
        if (!obj.success) throw new Exception(obj.message);
        if (obj.data == null) return default;
        return obj.data;
    }
}
